package edu.midir.demo.dao.impl;

import edu.midir.demo.dao.UserDAO;
import edu.midir.demo.pojo.domain.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

/**
 * @author yangzhi
 */
@Repository
public class UserDAOImpl implements UserDAO {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void saveUser(UserEntity userEntity) {
        mongoTemplate.save(userEntity);
    }

    @Override
    public UserEntity findUserByNickName(String nickName) {
        Query query = new Query(Criteria.where("nickName").is(nickName));
        return mongoTemplate.findOne(query, UserEntity.class);
    }

    @Override
    public void updateUser(UserEntity user) {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update=new Update()
                .set("userName",user.getNickName())
                .set("avatar",user.getAvatar())
                ;
        mongoTemplate.updateFirst(query,update,UserEntity.class);
    }

    @Override
    public void deleteUserById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, UserEntity.class);
    }
}
